<script setup>
import { reactive, ref, onMounted } from 'vue';
import { page, findByCG, deleteById } from "@/api/food";
import { findById } from "@/api/elderInfo";
import { useRouter } from "vue-router";

const router = useRouter();
const queryPageParam = reactive({
  name: '',
  pageNo: 1,
  pageSize: 5
});
const queryPageParamByCG = reactive({
  name: '',
  pageNo: 1,
  pageSize: 5
});
// 数据
const tableData = ref([]);
const total = ref(0);
const elderMap = ref({});
// 修改getElderName方法
const getElderName = async (elderlyId) => {
  if (!elderlyId) return '无名字';
  
  // 如果已经缓存过，直接返回
  if (elderMap.value[elderlyId]) {
    return elderMap.value[elderlyId];
  }
  
  try {
    const res = await findById(elderlyId);
    if (res.data && res.data.name) {
      elderMap.value[elderlyId] = res.data.name;
      return res.data.name;
    }
    return '未知姓名';
  } catch (error) {
    console.error('获取老人信息失败:', error);
    return '未知姓名';
  }
};
// 根据护理人查询食品信息
const handleQueryPageByCG = ()=>{
  findByCG(queryPageParamByCG).then(res=>{
    console.log(res)
    tableData.value = res.data.records;
    total.value = res.data.total;
  })
}

// 修改表格数据处理
const handleQueryPage = async () => {

  try {
    const res = await page(queryPageParam);
    tableData.value = res.data.records;
    total.value = res.data.total;
    
    // 预加载所有老人姓名
    await Promise.all(
      tableData.value.map(async (item) => {
        if (item.elderlyId) { // 确保使用正确的字段名
          await getElderName(item.elderlyId);
        }
      })
    );
  } catch (error) {
    console.error('查询数据失败:', error);
  }
};

// 修改每页数量的回调函数
const handleSizeChange = (sizeValue) => {
  queryPageParam.pageSize = sizeValue;
  handleQueryPage();
};

// 修改页码之后的回调函数
const handleCurrentChange = (currentValue) => {
  queryPageParam.pageNo = currentValue;
  handleQueryPage();
};

// 查看
const handleDetail = (id) => {
  router.push({
    path: '/foodInfo/detail',
    query: { id }
  });
};

// 编辑
const handleEdit = (id) => {
  router.push({
    path: '/foodInfo/save',
    query: { id }
  });
};

// 确认删除
const handleDeleteConfirm = (id) => {
  deleteById(id).then(() => {
    handleQueryPage(); // 删除成功后再次分页查询
  });
};

// 新增
const handleAdd = () => {
  router.push({
    path: '/foodInfo/save'
  });
};

// Vue 挂载完成之后执行钩子函数
onMounted(() => {
  handleQueryPage();
  
});
const getMealDescription = (mealId) => {
  const descriptions = {
    '0': '适合一般老年人的常规健康膳食',
    '1': '针对有轻微健康问题的老年人',
    '2': '平衡营养的标准健康膳食',
    '3': '富含营养的高标准健康膳食',
    '4': '针对特定医疗需求的特殊膳食',
    '5': '严格控制的极致健康膳食'
  };
  return descriptions[mealId] || '未知膳食类型';
};
</script>

<template>
  <div class="dashboard-container">
    <!-- 头部区域 -->
    <div class="dashboard-header">
      <div class="header-content">
        <h1 class="header-title">
          <el-icon class="title-icon"><Menu /></el-icon>
          膳食记录管理系统
        </h1>
        <div class="header-actions">
          <el-button type="success" round class="action-button" @click="handleAdd">
            <el-icon><Plus /></el-icon> 新增记录
          </el-button>
        </div>
      </div>
    </div>

    <!-- 控制面板 -->
    <div class="control-panel">
      <div class="search-section">
        <el-input 
          v-model="queryPageParam.name" 
          placeholder="请输入老人姓名" 
          class="search-input"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" class="search-button" @click="handleQueryPage">
          <el-icon><Search /></el-icon> 查询
        </el-button>
      </div>
      
      <div class="stats-section">
        <div class="stat-card">
          <div class="stat-value">{{ total }}</div>
          <div class="stat-label">总记录数</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">5</div>
          <div class="stat-label">膳食模板</div>
        </div>
        
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="data-table-container">
      <el-table 
        :data="tableData" 
        style="width: 100%" 
        stripe 
        highlight-current-row
        class="elegant-table"
      >
        <el-table-column prop="recordId" label="编号" width="80" align="center" />
        <el-table-column prop="elderlyId" label="老人编号" width="180" />
        <el-table-column label="老人姓名" width="180">
          <template v-slot="scope">
            <div class="elder-info">
              <el-avatar :size="36" class="elder-avatar">
                {{ elderMap[scope.row.elderlyId]?.charAt(0) || '长' }}
              </el-avatar>
              <span class="elder-name">
                {{ elderMap[scope.row.elderlyId] || '加载中...' }}
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="date" label="膳食日期" width="180" />
        <el-table-column prop="mealTime" label="用餐时间" width="180" />
        
        <el-table-column prop="status" label="用餐状态" width="180" align="center">
          <template #default="scope">
            <el-tag
              class="status-tag"
              :class="{
                'status-0': scope.row.status == '0',
                'status-1': scope.row.status == '1',
                'status-2': scope.row.status == '2',
                'status-3': scope.row.status == '3',
                'status-4': scope.row.status == '4'
              }"
            >
              {{ 
                {'0':'未食用','1':'已食用','2':'部分食用','3':'未提供','4':'异常'}[scope.row.status] 
              }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="mealId" label="膳食模板" width="150" align="center">
          <template #default="scope">
            <el-tooltip :content="getMealDescription(scope.row.mealId)" placement="top">
              <div class="meal-card">
                <div class="meal-icon">
                  <el-icon v-if="scope.row.mealId == '0'"><Food /></el-icon>
                  <el-icon v-if="scope.row.mealId == '1'"><Dish /></el-icon>
                  <el-icon v-if="scope.row.mealId == '2'"><Sugar /></el-icon>
                  <el-icon v-if="scope.row.mealId == '3'"><KnifeFork /></el-icon>
                  <el-icon v-if="scope.row.mealId == '4'"><MedicineBox /></el-icon>
                  <el-icon v-if="scope.row.mealId == '5'"><Star /></el-icon>
                </div>
                <span class="meal-name">
                  {{ 
                    {'0':'常规健康','1':'较健康','2':'健康','3':'非常健康','4':'医疗级','5':'极致健康'}[scope.row.mealId] 
                  }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        
        <el-table-column fixed="right" label="操作" min-width="200" align="center">
          <template #default="scope">
            <div class="action-buttons">
              <el-button 
                size="small" 
                class="view-button"
                @click="handleDetail(scope.row.recordId)"
              >
                <el-icon><View /></el-icon> 查看
              </el-button>
              <el-button 
                type="primary" 
                size="small" 
                class="edit-button"
                @click="handleEdit(scope.row.recordId)"
              >
                <el-icon><Edit /></el-icon> 编辑
              </el-button>
              <el-popconfirm 
                title="确定要删除这条记录吗？" 
                confirm-button-text="确定" 
                cancel-button-text="取消"
                @confirm="handleDeleteConfirm(scope.row.recordId)"
              >
                <template #reference>
                  <el-button type="danger" size="small" class="delete-button">
                    <el-icon><Delete /></el-icon> 删除
                  </el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页器 -->
    <div class="pagination-container">
      <el-pagination 
        v-model:current-page="queryPageParam.pageNo" 
        v-model:page-size="queryPageParam.pageSize"
        :page-sizes="[5, 10, 20, 30]" 
        background 
        layout="total, sizes, prev, pager, next, jumper"
        :total="total" 
        @size-change="handleSizeChange" 
        @current-change="handleCurrentChange"
        class="custom-pagination"
      />
    </div>
  </div>
</template>

<style scoped>
.dashboard-container {
  padding: 20px;
  font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4edf9 100%);
  min-height: 100vh;
}

/* 头部样式 */
.dashboard-header {
  background: linear-gradient(120deg, #4a6bdf 0%, #3a56c4 100%);
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(65, 105, 225, 0.3);
  margin-bottom: 24px;
  padding: 0 30px;
  color: white;
  overflow: hidden;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 0;
}

.header-title {
  display: flex;
  align-items: center;
  font-size: 24px;
  font-weight: 600;
  margin: 0;
}

.title-icon {
  font-size: 28px;
  margin-right: 15px;
  color: #ffd04b;
}

.action-button {
  height: 44px;
  padding: 0 24px;
  font-weight: 500;
  border: none;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.action-button:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
}

/* 控制面板样式 */
.control-panel {
  background: white;
  border-radius: 16px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.06);
}

.search-section {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
}

.search-input {
  flex: 1;
  max-width: 400px;
}

.search-input :deep(.el-input__inner) {
  height: 48px;
  border-radius: 12px;
  padding-left: 48px;
  font-size: 16px;
}

.search-button {
  height: 48px;
  padding: 0 32px;
  border-radius: 12px;
  font-weight: 500;
  font-size: 16px;
}

.stats-section {
  display: flex;
  gap: 24px;
}

.stat-card {
  flex: 1;
  background: linear-gradient(135deg, #f0f5ff 0%, #e6eeff 100%);
  border-radius: 16px;
  padding: 20px;
  text-align: center;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.08);
}

.stat-value {
  font-size: 32px;
  font-weight: 700;
  color: #4a6bdf;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 16px;
  color: #5a6d88;
}

/* 表格样式 */
.data-table-container {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.06);
  margin-bottom: 24px;
}

.elegant-table {
  --el-table-border-color: transparent;
  --el-table-header-bg-color: #f5f8ff;
  --el-table-row-hover-bg-color: #f0f7ff;
}

.elegant-table :deep(th) {
  background-color: #f5f8ff;
  color: #4a6bdf;
  font-weight: 600;
  height: 60px;
}

.elegant-table :deep(td) {
  height: 70px;
  border-bottom: 1px solid #f0f4f8;
}

.elder-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.elder-avatar {
  background: linear-gradient(135deg, #4a6bdf 0%, #3a56c4 100%);
  color: white;
  font-weight: bold;
}

.elder-name {
  font-weight: 500;
}

.status-tag {
  padding: 8px 16px;
  border-radius: 20px;
  font-weight: 500;
  border: none;
}

.status-0 { background: #e6e9f0; color: #5a6d88; }
.status-1 { background: #e8f5e9; color: #4caf50; }
.status-2 { background: #fff8e1; color: #ff9800; }
.status-3 { background: #f5f5f5; color: #9e9e9e; }
.status-4 { background: #ffebee; color: #f44336; }

.meal-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.meal-icon {
  width: 40px;
  height: 40px;
  background: linear-gradient(135deg, #f0f5ff 0%, #e6eeff 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #4a6bdf;
  font-size: 18px;
}

.meal-name {
  font-weight: 500;
  color: #4a6bdf;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.view-button, .edit-button, .delete-button {
  padding: 8px 16px;
  border-radius: 8px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: all 0.2s ease;
}

.view-button { background: #e3f2fd; color: #2196f3; }
.edit-button { background: #e8f5e9; color: #4caf50; }
.delete-button { background: #ffebee; color: #f44336; }

.view-button:hover, .edit-button:hover, .delete-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

/* 分页器样式 */
.pagination-container {
  display: flex;
  justify-content: center;
}

.custom-pagination {
  background: white;
  padding: 16px;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.06);
}

/* 响应式设计 */
@media (max-width: 992px) {
  .header-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .stats-section {
    flex-direction: column;
  }
  
  .action-buttons {
    flex-wrap: wrap;
    justify-content: center;
  }
}

@media (max-width: 768px) {
  .search-section {
    flex-direction: column;
  }
  
  .search-input {
    max-width: 100%;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 8px;
  }
  
  .action-buttons .el-button {
    width: 100%;
  }
}
</style>